package com.link.base.base.message.push.service;

import com.link.base.base.message.push.dao.mybatis.mapper.PushMapper;
import com.link.base.base.message.push.model.PushInfo;
import com.link.base.base.message.push.model.PushInfoInsert;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 消息管理 - 推送服务实现
 *
 * @author ouyangzhenqiang
 * @date 2018/10/26
 */
@Component
public class PushServiceImpl implements PushService {
    private static String yStr = "Y";
    @Resource
    private PushMapper pushMapper;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private JpushServiceImpl jpushServiceImpl;
    @Resource
    private WebPushServiceImpl webPushServiceImpl;

    @Override
    public void messageInsert(PushInfoInsert record) throws Exception {
        try {
            String appPushFlag = record.getAppPushFlag();
            String webPushFlag = record.getWebPushFlag();
            if (!yStr.equals(appPushFlag) && !yStr.equals(webPushFlag)) {
                appPushFlag = "Y";
                webPushFlag = "Y";
            }
            PushInfo pushInfo = new PushInfo();
            String pushTitle = StringUtils.isBlank(record.getPushTitle()) ? "通知" : record.getPushTitle();
            pushInfo.setPushTitle(pushTitle);
            pushInfo.setPushNote(record.getPushNote());
            pushInfo.setModule(record.getModule());
            pushInfo.setObjectId(record.getObjectId());
            String remindDt = record.getRemindDt();
            if (StringUtils.isBlank(remindDt)) {
                remindDt = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
            }
            pushInfo.setRemindDt(remindDt);
            pushInfo.setAppPushFlag(appPushFlag);
            pushInfo.setWebPushFlag(webPushFlag);
            List<Long> userList = record.getUserList();
            // 如果传递的消息接收用户列表为空，则观察下userId字段，以支持单独传递一个userId的情况
            if (userList == null || userList.size() == 0) {
                if (record.getUserId() == null) {
                    return;
                }
                userList = new ArrayList<>();
                userList.add(record.getUserId());
            }
            for (Long userId : userList) {
                pushInfo.setUserId(userId);
                pushInfo.setId(keyGenerateService.keyGenerate());
                pushInfo.interfaceCreateData(userId, userId, 0L);
                pushMapper.messageInsertByInterface(pushInfo);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            LCLogger.error().withMessageKey("messageInsert").withMessage("插入推送消息失败：" + e.toString()).flush();
            throw new Exception("插入推送消息失败：" + e.toString());
        }
    }

    @Override
    public void sampleMessageOnlyUser(String pushNote, Long userId) throws Exception {
        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushTitle("通知");
        pushInfo.setPushNote(pushNote);
        pushInfo.setUserId(userId);
        pushInfo.setId(keyGenerateService.keyGenerate());
        pushInfo.interfaceCreateData(userId, userId, 0L);
        pushInfo.setAppPushFlag("Y");
        pushInfo.setWebPushFlag("Y");
        pushInfo.setRemindDt(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        pushMapper.messageInsertByInterface(pushInfo);
    }

    @Override
    public void sampleMessageForModule(String pushNote, Long userId, Long objectId, String module) throws Exception {
        PushInfo pushInfo = new PushInfo();
        pushInfo.setPushTitle("通知");
        pushInfo.setPushNote(pushNote);
        pushInfo.setUserId(userId);
        pushInfo.setObjectId(objectId);
        pushInfo.setModule(module);
        pushInfo.setId(keyGenerateService.keyGenerate());
        pushInfo.interfaceCreateData(userId, userId, 0L);
        pushInfo.setAppPushFlag("Y");
        pushInfo.setWebPushFlag("Y");
        pushInfo.setRemindDt(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        pushMapper.messageInsertByInterface(pushInfo);
    }

    @Override
    public void pushInfoRightAway(String pushTitle, String pushNote, Long userId,
                                  String module, Long objectId, String appPushFlag, String webPushFlag) throws Exception {
        if (!yStr.equals(appPushFlag) && !yStr.equals(webPushFlag)) {
            appPushFlag = "Y";
            webPushFlag = "Y";
        }
        PushInfo pushInfo = new PushInfo();
        pushTitle = StringUtils.isBlank(pushTitle) ? "通知" : pushTitle;
        pushInfo.setPushTitle(pushTitle);
        pushInfo.setPushNote(pushNote);
        pushInfo.setUserId(userId);
        pushInfo.setModule(module);
        pushInfo.setObjectId(objectId);
        pushInfo.setAppPushFlag(appPushFlag);
        pushInfo.setWebPushFlag(webPushFlag);
        pushInfo.setRemindDt(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        pushInfo.setPushNowFlag("Y");
        pushInfo.setId(keyGenerateService.keyGenerate());
        pushInfo.interfaceCreateData(userId, userId, 0L);
        pushMapper.messageInsertByInterface(pushInfo);
        // 查询数据
        pushInfo = pushMapper.queryPushItemById(pushInfo);
        // 推送
        if (yStr.equals(appPushFlag)) {
            try {
                jpushServiceImpl.jPush(pushInfo);
                pushInfo.setAppDealFlag("Y");
                pushInfo.setAppDealMsg("ok");
            } catch (Exception e) {
                pushInfo.setAppDealFlag("Y");
                pushInfo.setAppDealMsg(e.getMessage());
                pushInfo.setAppFailNum("1");
            }
            // 更新推送结果
            pushMapper.updateAppPushResult(pushInfo);
        }
        if (yStr.equals(webPushFlag)) {
            webPushServiceImpl.webPushRightWay(pushInfo);
        }
    }
}